import {
  createContext,
  useCallback,
  useContext,
  useRef,
  useState,
  type PropsWithChildren,
} from "react";
import type { IDeviceStatus } from "@/lib/types";

type DeviceContext = {
  loading: boolean;
  device?: IDeviceStatus;
  deviceList: IDeviceStatus[];
  onLoad: () => void;
  onDeviceChange: (device?: IDeviceStatus) => void;
  onDeviceListChange: (deviceList: IDeviceStatus[]) => void;
  reloadDeviceList: () => void;
  onReloadDeviceListHandlerChange: (handler?: () => void) => void;
};

const deviceContext = createContext({} as DeviceContext);

export function useDeviceContext() {
  return useContext(deviceContext);
}

export default function DeviceProvider({ children }: PropsWithChildren) {
  const [device, setDevice] = useState<IDeviceStatus>();
  const [deviceList, setDeviceList] = useState<IDeviceStatus[]>([]);
  const [loading, setLoading] = useState(true);
  const reloadDeviceListHandlerRef = useRef<() => void>();
  const onLoad = useCallback(() => {
    setLoading(false);
  }, []);
  const reloadDeviceList = useCallback(() => {
    reloadDeviceListHandlerRef.current?.();
  }, []);
  const onReloadDeviceListHandlerChange = useCallback(
    (handler?: () => void) => {
      reloadDeviceListHandlerRef.current = handler;
    },
    [],
  );

  return (
    <deviceContext.Provider
      value={{
        device,
        deviceList,
        loading,
        onLoad,
        onDeviceChange: setDevice,
        onDeviceListChange: setDeviceList,
        reloadDeviceList,
        onReloadDeviceListHandlerChange,
      }}
    >
      {children}
    </deviceContext.Provider>
  );
}
